package com.thyrsus.project.helper;

import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.thyrsus.project.form.user.UserForm;
import com.thyrsus.project.object.UserContext;

public class UserHelper {

	static Logger LOGGER = Logger.getLogger(UserHelper.class);
	
	public static boolean isConnected(HttpServletRequest request) {
		SessionHelper.removeAttribute(request,Constants.ERROR_LOGIN);
		if (SessionHelper.getAttribute(request,Constants.USER_CONTEXT)==null) {
			return false;
		} else {
			SessionHelper.removeAttribute(request,Constants.LAST_URL);
			return true;
		}
	}
	
	public static UserContext getUser(HttpServletRequest request) {
		return (UserContext)request.getSession().getAttribute(Constants.USER_CONTEXT);
	}
	
	/**
	 * This function save the requested url, set the locale depending on the user language
	 * and send as a result the login URL
	 * @param request the request
	 * @param response the response
	 * @param url the current url
	 * @return
	 */
	public static String getLoginURL(HttpServletRequest request,HttpServletResponse response,String url) {
		SessionHelper.setAttribute(request,Constants.LAST_URL, url);
		if (SessionHelper.getAttribute(request, Constants.LOCALE)==null) {
			LocaleHelper.manageLocale(request, response);
		}
		return "/user/login";
	}
	
	public static String getLastURL(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String lastURL = (String)session.getAttribute(Constants.LAST_URL);
		session.removeAttribute(Constants.LAST_URL);
		return lastURL;
		
	}
	
	public static boolean validateUserForm(UserForm user) {
		if ("".equals(user.getFirstName()) || "".equals(user.getMail()) || "".equals(user.getPassword())
				|| "".equals(user.getDayBirthDate()) || "".equals(user.getMonthBirthDate())
				|| "".equals(user.getYearBirthDate())) {
			LOGGER.error("validateUserForm : empty field...");
			return false;
		}
		
		Calendar cal = GregorianCalendar.getInstance();
		try {
			cal.set(Integer.valueOf(user.getYearBirthDate()).intValue(),
				Integer.valueOf(user.getMonthBirthDate()).intValue(),
				Integer.valueOf(user.getDayBirthDate()).intValue());
		} catch (Exception e) {
			LOGGER.error("validateUserForm : wrong date ("+user.getDayBirthDate()+"/"+
					user.getMonthBirthDate()+"/"+user.getYearBirthDate());
			return false;
		}
		return true;
	}
}
